<?php
!defined('IN_ROOT') && exit( 'Access Denied' );
class DiscountController extends AdminModuleController 
{
	public function actionSetting() {
		if (getgpc('submitTo', 'P')) {
			$categoryId = getgpc('categoryId', 'P');
			$groups = getgpc('groups', 'P');
			
			foreach($groups as $k=>$v) {
				$discount = $this->DiscountModel->find("categoryId='$categoryId' AND groupId='$k'");
				if($discount) {
					$this->DiscountModel->updateByPk($discount['discountId'], array('discountRate'=>$v));
				} else {
					$this->DiscountModel->insert(array(
						'categoryId'=>$categoryId,
						'groupId'=>$k,
						'discountRate'=>$v,
						'createdTime'=>$this->time,
					));
				}
				// 更新未购买的购物车的折扣
				$shoppingcartList = $this->ShoppingcartModel->findAll("settleStatus='0'");
				foreach($shoppingcartList as $shoppingcart) {
					$user = $this->UserModel->findByPk($shoppingcart['userId']);
					$product = $this->ProductModel->findByPk($shoppingcart['productId']);
					if ($user && $product) {
						$discount = $this->getDiscount($user['groupId'], $product['upperparentId'], $product['parentId']);
						//echo $user['groupId'].'|'.$product['upperparentId'].'|'.$product['parentId'].'|'.$discount."<br/>";
						$this->ShoppingcartModel->updateByPk($shoppingcart['id'], array('discount'=>$discount));
					}
				}
			}
			$this->message('操作成功。', 'discount-setting-'.$categoryId.'.htm');
		}
		
		$categoryId = getgpc(2);
		$discountList = $this->DiscountModel->findAll("categoryId='$categoryId'");
		
		$category = $this->CategoryModel->findByPk($categoryId);
		$userGroupList = $this->UserGroupModel->findAll("groupId>='".GODHOUSE_GROUP_ADMIN_LIMIT."'");
		foreach($userGroupList as &$v) {
			$v['discountRate'] = 0;
			foreach ($discountList as $discount) {
				if($v['groupId'] == $discount['groupId']) {
					$v['discountRate'] = $discount['discountRate'];
				}
			}
		}
		
		$this->view->assign('userGroupList', $userGroupList);
		$this->view->assign('category', $category);
		$this->view->assign('discount', $discount);
		$this->display('discount_setting');
	}
	
	private function getDiscount($groupId, $upperparentId=0, $parentId=0) {
		$discount = 100;
		$discount = $this->DiscountModel->find("groupId='$groupId' AND categoryId='$parentId'");
		if($discount) {
			$discount = $discount['discountRate'];
		} else {
			$discount2 = $this->DiscountModel->find("groupId='$groupId' AND categoryId='$upperparentId'");
			if($discount2) {
				$discount = $discount2['discountRate'];
			}
		}
		$discount = $discount/100;
		return $discount;
	}
}